package cn.mhome.spring.thrift.server;

import java.io.File;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import cn.mhome.spring.thrift.server.config.FilePathConfig;

/**
 * spring BeanFactory
 * 获取thrift service bean
 */
public class ConfigCenter{

	protected static Logger logger = LoggerFactory.getLogger(ConfigCenter.class);
	private static Properties serverInfo = null;
	
	private static String defaultConfigPath = FilePathConfig.DEFAULT_SERVER_IPPORT.getPath();
	private static File defaultConfigFile = new File(defaultConfigPath);

	public static void readFromPropertiesFile() {
		try {
			boolean readed = false;
			if (readed == false) {
				try {
					Resource res = new FileSystemResource(defaultConfigPath);
					EncodedResource eres = new EncodedResource(res, "utf-8");
					serverInfo = PropertiesLoaderUtils.loadProperties(eres);
					readed = true;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (readed == false) {
				try {
					logger.info("read config from default appconfig.properties");
					Resource res = new ClassPathResource("configcenter.properties");
					EncodedResource eres = new EncodedResource(res, "utf-8");
					serverInfo = PropertiesLoaderUtils.loadProperties(eres);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else{
				if(defaultConfigFile != null && defaultConfigFile.exists()){
					logger.info("config.properties's absolutePath:"+defaultConfigFile.getAbsolutePath());
				}
			}
			if(readed == false){
				logger.error("error read config from configcenter.properties");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("error read config from configcenter.properties");
		}
	}

	static {
		readFromPropertiesFile();
    }
	
	
	public static String getServerIp(String serverName) {
		if (serverInfo.containsKey(serverName)) {
			String[] val = serverInfo.get(serverName).toString().split(":");
			return val[0];
		} else {
			return null;
		}
	}
	
	public static int getServerPort(String serverName) {
		if (serverInfo.containsKey(serverName)) {
			String[] val = serverInfo.get(serverName).toString().split(":");
			return Integer.parseInt(val[1]);
		} else {
			return 0;
		}
	}
	
	public static Properties getServerInfo(){
		return serverInfo;
	}
}
